package com.sky.service.impl;

import com.sky.context.BaseContext;
import com.sky.entity.AddressBook;
import com.sky.mapper.AddressMapper;
import com.sky.service.AddressService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class AddressServiceImpl implements AddressService {

    @Autowired
    private AddressMapper addressMapper;

    /**
     * 查询当前登录用户的所有地址信息
     *
     * @return
     */
    @Override
    public List<AddressBook> list() {
        //获取当前登录用户
        Long userId = BaseContext.getCurrentId();
        //查询数据
        List<AddressBook> addressBookList = addressMapper.findAllByUserId(userId);
        return addressBookList;
    }

    /**
     * 修改默认地址
     *
     * @param addressBook
     */
    @Transactional
    @Override
    public void setDefaultAddressBook(AddressBook addressBook) {
        //先将所有的地址默认值取消掉，然后再设置默认地址
        //将所有的地址默认值设置为0
        addressMapper.setDefault();
        //将地址设置为默认地址
        addressBook.setIsDefault(1);
        //修改
        addressMapper.update(addressBook);
    }

    /**
     * 修改地址
     *
     * @param addressBook
     */
    @Override
    public void update(AddressBook addressBook) {
        addressBook.setUserId(BaseContext.getCurrentId());
        addressMapper.update(addressBook);
    }

    /**
     * 根据id查询地址
     *
     * @param id
     * @return
     */
    @Override
    public AddressBook getAddressBookById(Long id) {
        AddressBook addressBook = addressMapper.getAddressBookById(id);
        return addressBook;
    }

    /**
     * 新增地址
     *
     * @param addressBook
     */
    @Override
    public void save(AddressBook addressBook) {
        addressBook.setUserId(BaseContext.getCurrentId());
        addressBook.setIsDefault(0);
        addressMapper.save(addressBook);
    }

    /**
     * 根据id删除地址
     *
     * @param id
     */
    @Override
    public void delete(Integer id) {
        addressMapper.delete(id);
    }
}
